<!--
 * @Description: 
 * @FilePath: \rs_wms_pc\src\views\invoice\preparation\index.vue
-->
<template>
  <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="100px">
        <el-form-item label="单据编号" prop="no">
          <el-input
            v-model="queryParams.no"
            placeholder="请输入单据编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单编号" prop="workOrderNo">
          <el-input
            v-model="queryParams.workOrderNo"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="orderStatus">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择状态">
              <el-option v-for="dict in dict.type.product_mp_apply_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" ref="btnGroup">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['bill:preparation:add']"
          >{{ $t("add") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="!(!single && selections[0].orderStatus == 1)"
            @click="handleUpdate"
            v-hasPermi="['bill:preparation:edit']"
          >{{ $t("edit") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-s-claim"
            size="mini"
            :disabled="!(!single && selections[0].orderStatus == 1)"
            @click="confirmPreparation"
            v-hasPermi="['bill.preparation:confirm']"
          >确定</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-message"
            size="mini"
            :disabled="!(!single &&[2,3].includes(selections[0].orderStatus))"
            @click="confirmDistribute"
            v-hasPermi="['bill.preparation:confirmDistribute']"
          >下发</el-button>
        </el-col>
        <el-col :span="1.5">
            <!-- :disabled="multiple" -->
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="!(!single && selections[0].orderStatus == 1)"
            @click="handleDelete"
            v-hasPermi="['bill:preparation:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['bill:preparation:import']"
          >{{ $t("import") }}</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>


      <el-table v-loading="loading"  :height="calcTableHeight"  :data="preparationList" @selection-change="handleSelectionChange" highlight-current-row @current-change="rowSelection">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" />
        <af-table-column label="单据编号" align="center" prop="no" />
        <el-table-column label="单据状态" align="center" prop="orderStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.product_mp_apply_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <af-table-column label="备料区编号" align="center" prop="storehouseAreaNo" />
        <af-table-column label="仓库编号" align="center" prop="storehouseNo" />
        <af-table-column label="工单编号" align="center" prop="workOrderNo" />
        <el-table-column label="工单数量" align="center" prop="workOrderQty" />
        <el-table-column label="完成时间" align="center" prop="completeTime" min-width="152">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.completeTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="152" />
        <el-table-column label="最后更新人" align="center" prop="updateBy" min-width="100"/>
        <el-table-column label="最后更新时间" align="center" prop="updateTime" min-width="152" />
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!--   单据明细 -->
      <el-tabs v-model="activeTab" type="card" ref="halfTable" class="half-table">
        <el-tab-pane label="备料清单" name="detailList">
          <detailList ref="detailList" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
        <el-tab-pane label="备料拣货单" name="pickList">
          <pickList ref="pickList" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
      </el-tabs>


    <!-- 添加或修改生产备料申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单编号" prop="workOrderNo">
          <el-input v-model="form.workOrderNo" placeholder="请输入工单编号" />
        </el-form-item>
        <el-form-item label="工单数量" prop="workOrderQty">
          <el-input-number v-model="form.workOrderQty" placeholder="请输入工单数量" :min="0" :precision="0"/>
        </el-form-item>
        <el-form-item label="仓库" prop="storehouseNo">
          <el-select style="width:100%;" v-model="form.storehouseNo" filterable placeholder="请选择仓库">
            <el-option
              v-for="dict in storehouseList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
              @click.native="changeStorehouse(dict, true)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备料区" prop="storehouseAreaNo">
          <el-select style="width:100%;" v-model="form.storehouseAreaNo" filterable placeholder="请选择备料区">
            <el-option
              v-for="dict in storehouseAreaList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
              @click.native="changeStorehouseAreaNo(dict, true)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t("importTip1") }}<em>{{ $t("clickUpload") }}</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>{{ $t("importTip") }}</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">{{ $t("download") }}</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t("sure") }}</el-button>
        <el-button @click="upload.open = false">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <distributeDialog ref="distributeDialog" :info="selections[0]"/>
  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { listPreparation, getPreparation, delPreparation, addPreparation, updatePreparation, confirmPreparation } from "@/api/invoice/preparation";
import { getToken } from "@/utils/auth"
import { listStorehouse } from "@/api/basic/storehouse";
import { listArea } from "@/api/basic/area";
import detailList from "./detailList"
import pickList from "./pickList"
import distributeDialog from "./distributeDialog"

export default {
  name: "Preparation",
  dicts: ["product_mp_apply_status"],
  mixins:[mixins],
  components: { detailList, pickList, distributeDialog },
  provide() {
    return {
      refresh:this.getList
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产备料申请表格数据
      preparationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        orderStatus: null,
        storehouseAreaNo: null,
        storehouseNo: null,
        workOrderNo: null,
        workOrderQty: null,
        completeTime: null,
        sort: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workOrderNo: [
          { required: true, message: "工单编号不能为空", trigger: "blur" }
        ],
        workOrderQty: [
          { required: true, message: "工单数量不能为空", trigger: "blur" }
        ],
        storehouseNo: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        storehouseAreaNo: [
          { required: true, message: "备料区不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bill/preparation/importExcel",
      },
      storehouseList: [],
      storehouseAreaList: [],
      //传递给订单详情的数据
      orderData: {},
      activeTab: 'detailList',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产备料申请列表 */
    getList() {
      this.loading = true;
      listPreparation(this.queryParams).then(response => {
        this.preparationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        orderStatus: null,
        storehouseAreaNo: null,
        storehouseNo: null,
        workOrderNo: null,
        workOrderQty: null,
        completeTime: null,
        remark: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        sort: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.rowSelection({});
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.rowSelection({});
      this.handleQuery();
    },
    //行选择
    rowSelection(row) {
      this.orderData = row
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.ids = selection.map(item => item.id)
      this.selections = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getStorehouseList()
      this.open = true;
      this.title = "添加生产备料申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.getStorehouseList()
      getPreparation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产备料申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePreparation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPreparation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.resetQuery();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除"' + ids.length + '"条数据项？').then(function() {
        return delPreparation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bill/preparation/export', {
        ...this.queryParams
      }, `preparation_${new Date().getTime()}.xlsx`)
    },
    
    /** 确认 */
    confirmPreparation(row) {
      this.reset();
      const id = row.id || this.ids[0];
      this.$modal
        .confirm(this.$t("confirmTip"))
        .then(function () {
          return confirmPreparation(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => {})
    },
    // 下发
    confirmDistribute(){
      this.$refs.distributeDialog.visible = true
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "生产备料申请导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("bill/preparation/importTemplate", {}, `生产备料申请模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 获取仓库列表 */
    getStorehouseList(){
      listStorehouse().then(response => {
        this.storehouseList = response.rows;
      });
    },
    // 仓库变更
    changeStorehouse(row){
      this.form.storehouseName = row.name;
      this.$set(this.form,'storehouseAreaNo','');
      this.$set(this.form,'storehouseAreaName','');
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      // 查询仓库下的库位
      listArea({
        storehouseNo:this.form.storehouseNo,
        whetherMp:'Y',
        pageSize:0,
      }).then(response => {
        this.$set(this,'storehouseAreaList',response.rows);
      });
      // this.getListStorehouseList(row.no, this.form.productNo);
    },
    // 备料区变更
    changeStorehouseAreaNo(row){
      this.form.storehouseAreaName = row.name;
    },
  }
};
</script>
